<?php
namespace ZL\Wechat;

use ZL\Wechat\entApiOauth;
/**
 * Description of EnterpriseHelper
 *
 * @author John
 */
class EnterpriseHelper {
     /**
        * 获取部门
        */
        public $token;

        public function __construct($token) {
            $this->token = $token;
        }

        public function getDepartmentByID($id = 1)
        {
            $url = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=".$this->_getAccessToken()."&id=".$id;
            $res = $this->https_request($url);
            return $res;
        }

        /*
         * 获取部门成员
         */
        public function getMemebersByDeptId($id = 1,$child = 0)
        {
            $accessToken = $this->_getAccessToken();
            $url = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token=$accessToken&department_id=$id&fetch_child=$child&status=STATUS";
            $res = $this->https_request($url);
            dump($res);
        }

        /*
         * 获取部门成员详情
         */
        public function getMemebersDetailByDeptId($id = 1,$child = 0)
        {
            $accessToken = $this->_getAccessToken();
            $url = "https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=$accessToken&department_id=$id&fetch_child=$child&status=STATUS";
            $res = $this->https_request($url);
    //            echo 1;
    //            myDump($res);die;
            return $res;
        }

         /*
        * 发送文本消息
        */
        public function sendTextMessage(){
            $accessToken = $this->_getAccessToken();
            $url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=$accessToken";

            $sdata = array();
            //$sdata['touser'] = "hackcat";
            $sdata["msgtype"] = "text";
            $sdata['toparty'] = "3";
            $text['content'] = "合理";
            $sdata['text'] = $text;
            $sdata['agentid'] = 2;


            $info1 = $this->toJson($sdata);

            echo $info1;

            $res = $this->curlPost($url,"post",$info1);
            dump($res);

        }

        /*
         * 获取标签列表
         */
        public function getTags(){
            $accessToken = $this->_getAccessToken();
            $url = "https://qyapi.weixin.qq.com/cgi-bin/tag/list?access_token=$accessToken";
            $res = $this->https_request($url);
            return $res;
        }

        /*
        * 发送文本消息
        */
        public function sendNewsMessage($userid,$article){
            $accessToken = $this->_getAccessToken();
            $url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=$accessToken";

            $sdata = array();
            $sdata['touser'] = $userid;
            $sdata["msgtype"] = "news";

            /*
            $news['articles'] = array(
                array(
                    "title" => "哈哈哈",
                    "description" => "嘿嘿嘿",
                    "url"   => "http://www.baidu.com",
                    "picurl"    => "http://wxsmart.wx91go.com/phpmyadmin/themes/pmahomme/img/logo_left.png",
                ),
                array(
                    "title" => "哈哈哈",
                    "description" => "嘿嘿嘿",
                    "url"   => "http://www.baidu.com",
                    "picurl"    => "http://wxsmart.wx91go.com/phpmyadmin/themes/pmahomme/img/logo_left.png",
                ),
            );

             *
             */
            $news['articles'] = array($article);
            $sdata['news'] = $news;
            $sdata['agentid'] = 2;      //企业应用id


            $info1 = $this->toJson($sdata);



            $res = $this->curlPost($url,"post",$info1);
            //dump($res);
            return $res;

        }

    public function createUser($data)
    {
       $accessToken = $this->_getAccessToken();
       $url = "https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=$accessToken";
       $json_data = $this->toJson($data);
       $res = $this->curlPost($url,"post",$json_data);
       return $res;
    }
    public function updateUser($data)
    {
       $accessToken = $this->_getAccessToken();
       $url = "https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token=$accessToken";
       $json_data = $this->toJson($data);
       $res = $this->curlPost($url,"post",$json_data);
       return $res;
    }
    public function deleteUser($userid)
    {
       $accessToken = $this->_getAccessToken();
       $url = "https://qyapi.weixin.qq.com/cgi-bin/user/delete?access_token=$accessToken&userid=$userid";
//       $json_data = $this->toJson($data);
       $res = $this->curlPost($url,"get",'');
       return $res;
    }
    public function getUser($userId)
    {
       $accessToken = $this->_getAccessToken();
       $url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=$accessToken&userid=$userId";
       $res = $this->curlPost($url,"get");
       return $res;
    }
    //部门
    public function createDept($data)
    {
       $accessToken = $this->_getAccessToken();
       $url = "https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token=$accessToken";
       $json_data = $this->toJson($data);
       $res = $this->curlPost($url,"post",$json_data);
       return $res;
    }
    public function updateDept($data)
    {
        $accessToken = $this->_getAccessToken();
        $url = "https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token=$accessToken";
        $json_data = $this->toJson($data);
        $res = $this->curlPost($url,"post",$json_data);
        return $res;
    }
    public function deleteDept($id)
    {
        $accessToken = $this->_getAccessToken();
        $url = "https://qyapi.weixin.qq.com/cgi-bin/department/delete?access_token=$accessToken&id=$id";
//       $json_data = $this->toJson($data);
        $res = $this->curlPost($url,"get",'');
        return $res;
    }

    private function toJson($data)
    {
            if (version_compare(PHP_VERSION,'5.4.0','<'))
        {
            $str = json_encode($data);
            $str = preg_replace_callback(
                                        "#\\\u([0-9a-f]{4})#i",
                                        function($matchs)
                                        {
                                             return iconv('UCS-2BE', 'UTF-8', pack('H4', $matchs[1]));
                                        },
                                         $str
                                        );
             $str =  $str;
        }
        else
        {
            $str =  json_encode($data, JSON_UNESCAPED_UNICODE);
        }

            return $str;
    }

    private function _getAccessToken()
    {
        $where = array('token' => $this->token);
        $wxuser = M("Wxuser",'tp_','DB_WX')->where($where)->find();
    //        myDump($wxuser);die;
        $apiOauth = new entApiOauth();
        $access_token = $apiOauth->update_authorizer_access_token($wxuser['ent_appid']);
    //            myDump($access_token);
        return $access_token;
    }

    public function curlPost($url, $method = 'post', $data = '')
    {
        $ch = curl_init();
        $header = 'Accept-Charset: utf-8';
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $temp = curl_exec($ch);
        return $temp;
    }

    public function https_request($url, $data = null)
    {
        $curl = curl_init();
        $header = "Accept-Charset: utf-8";
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        //curl_setopt($curl, CURLOPT_SSLVERSION, 3);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        $errorno= curl_errno($curl);
        if ($errorno) {
            return array('curl'=>false,'errorno'=>$errorno);
        }else{
            $res = json_decode($output,1);

            if ($res['errcode']){
                return array('errcode'=>$res['errcode'],'errmsg'=>$res['errmsg']);
            }else{
                return $res;
            }
        }
        curl_close($curl);
	}
}
